// 基本地址
// const baseURL: string = 'https://weather.cma.cn';
const baseURL = 'http://localhost:8080';
// 请求拦截器配置信息
const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    const {url} = options;
    options.url = baseURL + url;
    options.timeout = 9000;
    options.header = {
      ...options.header,
      'source-client': 'miniapp'
    };
    // 拿到token
    const token = '';
    if (token) {
      options.header.Authorization = `Bearer ${token}`;
    }

    options.header.Cookie = '_trs_uv=lyo3we6i_6252_8qog; Hm_lvt_c758855eca53e5d78186936566552a13=1721115780,1723173325,1723279931; HMACCOUNT=28A580B2C1918955; _trs_ua_s_1=lznwdkx6_6252_1yqw; Hm_lpvt_c758855eca53e5d78186936566552a13=1723280173';
    uni.showLoading({
      title: '加载中'
    });
  }
};

// 添加请求拦截器
uni.addInterceptor('request', httpInterceptor);


// 封装响应拦截器
uni.addInterceptor('response', {});
// 封装请求方法
export const Request = <T>(option: UniApp.RequestOptions) => {
  return new Promise<ResponseData<T>>((resolve, reject) => {
    uni.request({
      ...option,
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as ResponseData<T>);
        } else if (res.statusCode === 401) {
          // 清空token 回到登录页
          uni.navigateTo({url: '/pages/login/login'});
          reject(res);
        } else {
          uni.showToast({
            title: (res.data as ResponseData<T>).message,
            icon: 'none'
          });
          reject(res);
        }
      },
      fail(err) {
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        });
        reject(err);
      }
    });
  });
};

interface ResponseData<T> {
  code: number;
  data: T;
  message: string;
}